package com.acme.service.bank.impl;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.domain.bank.Gender;
import com.acme.exceptions.ClientExistsException;
import com.acme.service.bank.BankService;

public class BankServiceImpl implements BankService {

	public void saveBank(final Bank bank, final String pathTo)
			throws IOException {
		String path = "bank.ser";
		System.out.print("Start to serialaze bank into file: " + path);
		FileOutputStream fos = new FileOutputStream(path);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(bank);
		oos.flush();
		oos.close();
		fos.close();
		System.out.println(" ... Finish to serialaze.");
	}

	public Bank loadBank(final String pathFrom) throws IOException {
		String path = "bank.ser";
		System.out.print("Start to Deserialaze bank from file: " + path);
		FileInputStream fis = new FileInputStream(path);
		ObjectInputStream ois = new ObjectInputStream(fis);
		Bank bank = null;
		try {
			bank = (Bank) ois.readObject();
		} catch (ClassNotFoundException e) {
			System.out.println("File " + path
					+ " doesn't contain the Bank oject");
			e.printStackTrace();
		}
		ois.close();
		fis.close();
		System.out.println(" ... Finish to DEserialaze.");
		System.out.println(bank);
		return bank;

	}

	@Override
	public Client addClient(Bank bank, String name, Gender gender)
			throws ClientExistsException {
		Client cl = new Client(name, gender);
		bank.addClient(cl);
		try {
			saveBank(bank, "");
		} catch (IOException e) {
			System.out.println("ERROR: Serialization failed");
			e.printStackTrace();
		}
		
		return cl;
	}

}
